package com.itheima.service.impl;

import com.itheima.common.BaseContext;
import com.itheima.common.constant.LoginConstant;
import com.itheima.dto.UserLogDTO;
import com.itheima.entity.YddUser;
import com.itheima.entity.YddUserInfo;
import com.itheima.exception.BusinessException;
import com.itheima.mapper.HomeIndexMapper;
import com.itheima.service.HomeIndexService;
import com.itheima.utils.JwtUtils;
import com.itheima.vo.HomeDataVO;
import com.itheima.vo.UserLoginVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Objects;

@Service
@RequiredArgsConstructor
@Slf4j
public class HomeIndexServiceImpl implements HomeIndexService {
    private final JwtUtils jwtUtils;

    private final HomeIndexMapper homeIndexMapper;

    @Override
    @Transactional
    public UserLoginVO login(UserLogDTO userLoginDTO) {
        YddUser yddUser = homeIndexMapper.selectByUserName(userLoginDTO.getMobile());
        if (Objects.isNull(yddUser)) {
            throw new BusinessException("账号不正确");
        }
        String digest = DigestUtils.md5DigestAsHex(userLoginDTO.getPassword().getBytes());
        if (!Objects.equals(digest, yddUser.getPassword())) {
            throw new BusinessException("密码不正确");
        }
        HashMap<String, Object> map = new HashMap<>(8);
        map.put(LoginConstant.USER_ID, yddUser.getId());
        String jwt = jwtUtils.createJWT(map);
        return UserLoginVO.builder().token(jwt).build();
    }

    @Override
    public HomeDataVO getUserInfo() {
        HomeDataVO homeDataVO = new HomeDataVO();
        Integer userId = BaseContext.getUserId();
        YddUserInfo yddUser = homeIndexMapper.selectByUserId(userId);
        String username = yddUser.getUsername();
        Integer articleNum = homeIndexMapper.getArticleNumByName(username);
        homeDataVO.setUserInfo(yddUser);
        homeDataVO.setArticleNum(articleNum);
/*        List<Integer> zanNum = homeIndexMapper.getZanNumByName(userId);
        int c = 0;
        for (Integer i : zanNum) {
            c += i;
        }*/
        homeDataVO.setZanNum(0);
/*        List<Integer> collectNum = homeIndexMapper.getCollectNumByName(username);
        int nums = 0;
        for (Integer i : collectNum) {
            nums += i;
        }*/
        homeDataVO.setCollectNum(0);
        return homeDataVO;
    }
}
